package com.ljt.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljt.response.Result;
import com.ljt.response.ResultCode;
import com.ljt.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JWTLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private JWTUtil jwtUtil;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        if(authentication!=null){
            new SecurityContextLogoutHandler().logout(httpServletRequest,response,authentication);
        }

        Result result = Result.ok().message(ResultCode.LOGIN_SUCCESS.getMessage());
        //处理编码方式，防止中文乱码的情况
        response.setContentType("text/json;charset=utf-8");

        // 清除jwt
        response.setHeader(jwtUtil.getHead(), "");
        //塞到HttpServletResponse中返回给前台
        //这是springboot中jackson给我们提供的一种能将类或者其他对象转成json的方式
        response.getWriter().write(new ObjectMapper().writeValueAsString(result));
    }
}
